package com.fatmeraid.service.impl;

import com.alipay.api.internal.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fatmeraid.common.exception.FarmException;
import com.fatmeraid.common.login.LoginUser;
import com.fatmeraid.common.login.LoginUserHolder;
import com.fatmeraid.common.model.PageResult;
import com.fatmeraid.common.result.ResultCodeEnum;
import com.fatmeraid.dao.FarmerApplicationDao;
import com.fatmeraid.dao.UserDao;
import com.fatmeraid.domain.FarmerApplication;
import com.fatmeraid.domain.User;
import com.fatmeraid.service.FarmerApplicationService;
import com.fatmeraid.vo.PaginationVo;
import com.fatmeraid.vo.farmerApplication.AuditVo;
import com.fatmeraid.vo.farmerApplication.RegistrationVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;

@Service
public class FarmerApplicationServiceImpl implements FarmerApplicationService {
	@Autowired
	private FarmerApplicationDao farmerApplicationDao;

	@Autowired
	private UserDao userDao;

	// 提交申请
	@Override
	public Integer submitApplication(RegistrationVo registrationVo) {
		if (registrationVo == null){
			throw new FarmException(ResultCodeEnum.FAIL);
		}
		LoginUser loginUser = LoginUserHolder.getLoginUser();
		Long userId = loginUser.getUserId();
		FarmerApplication farmerApplication = new FarmerApplication();
		farmerApplication.setUserId(userId);
		farmerApplication.setRealName(registrationVo.getRealName());
		farmerApplication.setIdCard(registrationVo.getIdCard());
		farmerApplication.setFarmerProof(registrationVo.getFarmerProof());
		farmerApplication.setApplicationContent(registrationVo.getApplicationContent());

		int insert = farmerApplicationDao.insert(farmerApplication);
		if(insert<=0){
			throw new FarmException(ResultCodeEnum.FAIL);
		}
		Integer id = farmerApplication.getApplicationId();
		return id;
	}

	// 审核农户申请
	@Override
	public boolean auditApplication(AuditVo auditVo) {
		LoginUser loginUser = LoginUserHolder.getLoginUser();
		Long userId = loginUser.getUserId();
		// 判断当前权限是否为管理员
		if (userDao.selectById(userId).getRoleType()!=3){
			throw new FarmException(ResultCodeEnum.ADMIN_ACCESS_FORBIDDEN);
		}
		// 获取申请
		Integer id = auditVo.getApplicationId();
		FarmerApplication farmerApplication = farmerApplicationDao.selectById(id);

		// 请求参数不符合
		if(auditVo.getStatus()!=1&&auditVo.getStatus()!=2){
			throw new FarmException(ResultCodeEnum.FAIL);
		}

		// 将当前时间戳转换为LocalDateTime
		LocalDateTime auditTime = LocalDateTime.ofInstant(
				Instant.ofEpochMilli(System.currentTimeMillis()),
				ZoneId.systemDefault() // 使用系统默认时区
		);

		// 更新申请
		LambdaUpdateWrapper<FarmerApplication> luw = new LambdaUpdateWrapper<>();
		luw.eq(FarmerApplication::getApplicationId, auditVo.getApplicationId());
		luw.set(FarmerApplication::getAuditTime, auditTime);
		luw.set(FarmerApplication::getStatus, auditVo.getStatus());
		luw.set(FarmerApplication::getAuditorId, userId);
		if (auditVo.getAuditRemark()!=null||!auditVo.getAuditRemark().isEmpty()){
			luw.set(FarmerApplication::getAuditRemark, auditVo.getAuditRemark());
		}
		int insert = farmerApplicationDao.update(luw);
		if(insert<=0){
			throw new FarmException(ResultCodeEnum.FAIL);
		}

		// FarmerApplication审核通过, 将用户角色改为农户
		if (auditVo.getStatus()==1){
			LambdaUpdateWrapper<User> luw2 = new LambdaUpdateWrapper<>();
			luw2.eq(User::getUserId, farmerApplication.getUserId());
			luw2.set(User::getRoleType, 2);
			int update = userDao.update(luw2);
			if(update<=0){
				throw new FarmException(ResultCodeEnum.FAIL);
			}
		}
		return true;
	}

	// 获取农户申请列表
	@Override
	public PageResult<FarmerApplication> getFarmerApplicationList(PaginationVo paginationVo) {
		// 判断当前权限是否为管理员或者农户
		LoginUser loginUser = LoginUserHolder.getLoginUser();
		Long userId = loginUser.getUserId();
		Integer roleType = userDao.selectById(userId).getRoleType();
		if (roleType != 3&& roleType != 2 && roleType != 1) {
			throw new FarmException(ResultCodeEnum.ADMIN_ACCESS_FORBIDDEN);
		}

		// 创建分页对象
		IPage<FarmerApplication> page = new Page<>(paginationVo.getCurrent(), paginationVo.getSize());
		// 创建查询条件
		QueryWrapper<FarmerApplication> queryWrapper = new QueryWrapper<>();
		if (paginationVo.getKeyword() != null && !paginationVo.getKeyword().isEmpty()) {
			queryWrapper.like("real_name", paginationVo.getKeyword());
		}
		// 农户权限只查看自己申请
		if (roleType == 2 || roleType == 1){
			queryWrapper.eq("user_id", userId);
		}
		queryWrapper.orderByDesc("apply_time");
		// 执行分页查询
		IPage<FarmerApplication> farmerApplicationIPage = farmerApplicationDao.selectPage(page, queryWrapper);
		// 构造返回结果
		PageResult<FarmerApplication> pageResult = new PageResult<>(farmerApplicationIPage.getTotal(), farmerApplicationIPage.getRecords());
		return pageResult;
	}

	@Override
	public FarmerApplication getFarmerApplicationById(Long id) {
		// 判断当前权限是否为管理员或者农户
		LoginUser loginUser = LoginUserHolder.getLoginUser();
		Long userId = loginUser.getUserId();
		Integer roleType = userDao.selectById(userId).getRoleType();
		if (roleType != 3|| roleType != 2) {
			throw new FarmException(ResultCodeEnum.ADMIN_ACCESS_FORBIDDEN);
		}

		// 判断输入id是否合法
		 if (id == null||id<0) {
			 throw new FarmException(ResultCodeEnum.PARAM_ERROR);
		 }
		FarmerApplication farmerApplication = farmerApplicationDao.selectById(id);
		return farmerApplication;
	}
}
